import {app, BrowserWindow, ipcMain} from 'electron'
import path from 'path'
import axios, {AxiosRequestConfig} from 'axios'

const isDev = process.env.NODE_ENV === 'development'
const API_BASE = process.env.DS_API_BASE || 'http://localhost:8080'

let win: BrowserWindow | null = null

async function createWindow() {
  win = new BrowserWindow({
    width: 1280,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
    },
  })

  if (isDev) {
    await win.loadURL('http://localhost:5173')
    win.webContents.openDevTools()
  } else {
    await win.loadFile(path.join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// 通过主进程代理 HTTP 请求以规避跨域
ipcMain.handle('api:request', async (_event, options: {
  url: string
  method?: AxiosRequestConfig['method']
  data?: any
  params?: any
  headers?: Record<string, string>
}) => {
  const { url, method = 'POST', data, params, headers } = options
  const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`

  const config: AxiosRequestConfig = {
    url: fullUrl,
    method,
    data,
    params,
    headers,
    timeout: 30000,
  }

  const res = await axios.request(config)
  return res.data
})